//
//  JXLRefreshControl.swift
//  MicroBlog
//
//  Created by 贾晓磊 on 16/10/3.
//  Copyright © 2016年 贾晓磊. All rights reserved.
//

import UIKit

private let JXLRefreshControlHeight: CGFloat = 50

enum JXLRefreshControlState {
    //下拉刷新
    case normal
    //松手就刷新
    case pulling
    //正在刷新
    case refreshing
    
}

class JXLRefreshControl: UIControl {
    
    //纪录当前滚动视图
    var currentScrollView: UIScrollView?
    
    //当前控件的刷新状态
    var JXLState: JXLRefreshControlState = .normal {
        didSet{
            switch JXLState {
            case .normal:
                //  箭头重置,箭头显示, 停止风火轮, 更新显示内容
                iconImageView.isHidden = false
                UIView.animate(withDuration: 0.25, animations: {
                    self.iconImageView.transform = .identity
                })
                indicatorView.stopAnimating()
                
                //如果上一次状态是刷新状态，需要恢复原位
                //  oldValue表示上一次记录的结果
                if oldValue == .refreshing {
                    UIView.animate(withDuration: 0.25, animations: {
                        self.currentScrollView?.contentInset.top -= JXLRefreshControlHeight
                    })
                }
                messageLabel.text = "下拉刷新"
                
            case .pulling:
                // 箭头调转, 更新内容
                UIView.animate(withDuration: 0.25, animations: {
                    self.iconImageView.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI))
                })
                messageLabel.text = "松手刷新"
                
            case .refreshing:
                //  隐藏箭头, 开启菊花转, 更新显示内容
                iconImageView.isHidden = true
                indicatorView.startAnimating()
                messageLabel.text = "正在刷新..."
                
                //设置停留
                UIView.animate(withDuration: 0.25, animations: { 
                    self.currentScrollView?.contentInset.top += JXLRefreshControlHeight
                })
                
                //主动发送事件，刷新数据请求
                sendActions(for: .valueChanged)
                
            }
        }
    }
    
    //MARK: 懒加载子控件
    //下拉箭头
    private lazy var iconImageView: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    //风火轮
    private lazy var indicatorView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .gray)
    //文本
    private lazy var messageLabel: UILabel = {
        
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 12)
        label.textColor = UIColor.gray
        label.text = "下拉刷新"
        label.textAlignment = .center
        
        return label
        
    }()
    
    //重写init方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        //        self.frame.size = CGSize(width: ScreenWidth, height: JXLRefreshControlHeight)
        //        self.frame.origin.y = -JXLRefreshControlHeight
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //使用此方法获取父控件
    override func willMove(toSuperview newSuperview: UIView?) {
        guard let scrollView = newSuperview as? UIScrollView else {
            return
        }
        
        //代码执行到此，表示我们的父视图可以滚动
        self.frame.size = CGSize(width: ScreenWidth, height: JXLRefreshControlHeight)
        self.frame.origin.y = -JXLRefreshControlHeight
        
        //  kvo的方式监听 垂直方向的偏移量
        //  [.new, .old]->关系多个枚举
        scrollView.addObserver(self, forKeyPath: "contentOffset", options: .new, context: nil)
        //  记录当前的滚动的视图
        currentScrollView = scrollView
    }
    
    //  kvo监听方法, 只要contentOffset属性发生了改变,那么就会回到这个方法
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        //print(currentScrollView?.contentOffset.y)
        
        //偏移量
        let contentOffSetY = currentScrollView!.contentOffset.y
        
        //临界点
        let maxY = -(currentScrollView!.contentInset.top + JXLRefreshControlHeight)
        
        if currentScrollView!.isDragging {
            //拖动情况下有两种状态，1，下拉刷新状态，2，松手刷新状态
            //拖动状态
            if contentOffSetY < maxY && JXLState == .normal {
                //下拉超过临界值，松手开始刷新
                print("松手刷新normal")
                JXLState = .pulling
            } else if contentOffSetY >= maxY && JXLState == .pulling {
                //下拉没有超过临界值，松手
                print("下拉刷新normal")
                JXLState = .normal
            }
        } else {
            //没有拖动
            //要想进入正在刷新，第一个条件是没有拖动，第二个条件，是松手刷新的状态才可以进入正在刷新
            if JXLState == .pulling {
                print("正在刷新")
                JXLState = .refreshing
            }
        }
        
        
        
    }
    
    //结束刷新
    func endRefreshing() {
        JXLState = .normal
    }
    
    //移除kvo
    deinit {
        currentScrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    func setupUI() {
        backgroundColor = UIColor.red
        addSubview(iconImageView)
        addSubview(indicatorView)
        addSubview(messageLabel)
        
        //使用手写方式布局
        iconImageView.translatesAutoresizingMaskIntoConstraints = false
        indicatorView.translatesAutoresizingMaskIntoConstraints = false
        messageLabel.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: iconImageView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: -35))
        
        addConstraint(NSLayoutConstraint(item: iconImageView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1, constant: 0))
        
        
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .leading, relatedBy: .equal, toItem: iconImageView, attribute: .trailing, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .centerY, relatedBy: .equal, toItem: iconImageView, attribute: .centerY, multiplier: 1, constant: 0))
        
        
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: .centerX, relatedBy: .equal, toItem: iconImageView, attribute: .centerX, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: .centerY, relatedBy: .equal, toItem: iconImageView, attribute: .centerY, multiplier: 1, constant: 0))
        
        //        indicatorView.startAnimating()
        
    }
    
    
}
